package com.allen.utils;

import java.util.Calendar;
import java.util.TimeZone;

/**
 * 该工具用于测试性能时候的时间统计
 * 计算暂时只支持到24小时内
 * @author allen
 *
 */
public class TimerUtils {
	   private static final String TIME_ZONE = "CTS-6:00";
	   private static ThreadLocal<TimerUtils> timerUtils = new ThreadLocal<TimerUtils>();
	   long startTime = 0;
	   long endTime = 0;
	   Calendar calendar = Calendar.getInstance();
	   
	   private TimerUtils(){}

	   public static TimerUtils getInstance(){
		   return new TimerUtils();
	   }
	   
	   public static synchronized TimerUtils getInstanceLocal() {
		   TimerUtils utils = timerUtils.get();
		   if (null == utils) {
			   utils = getInstance();
			   timerUtils.set(utils);
		   }
		   return utils;
	   }
	   
	   /**
	    * 开始统计
	    */
	   public void start() {
		   startTime = System.currentTimeMillis();
	   }
	   
	   /**
	    * 结束统计
	    */
	   public void end() {
		   endTime = System.currentTimeMillis();
	   }
	   
	   /**
	    * 时间清零
	    */
	   public void clear(){
		   startTime = 0;
		   endTime = 0;
	   }
	   
	   /**
	    * 获取时间差
	    * @return
	    */
	   public long getTimeSpanInMillis(){
		   return endTime-startTime;
	   }
	   
	   @Override
	   public String toString(){
		 calendar.setTimeZone(TimeZone.getTimeZone(TIME_ZONE));
		 calendar.setTimeInMillis(endTime - startTime);
		 return calendar.get(Calendar.HOUR)+"时"+calendar.get(Calendar.MINUTE)
				 +"分"+calendar.get(Calendar.SECOND)+"秒"+calendar.get(Calendar.MILLISECOND)+"毫秒";
	   }
	   
	   
	   /**
	    * 使用例子
	    * @param args
	    */
	   public static void main(String[] args){
		   /**
		    * 例子1:比较具有灵活性，可自由设置统计的开始结束点
		    */
		   TimerUtils timer = TimerUtils.getInstance();
		   timer.start();
				try {
					//假设程序运行了3秒
					Thread.sleep(3000);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
		   timer.end();
		   System.out.println(timer);
	   }
}
